#include "file/fdebug.h"
#include "display/PSD_Chart_Painter.h"
#include <QTimer>

PSD_Chart_Painter::PSD_Chart_Painter(QChartView *parent) : QChartView(parent)
{
    series = new QLineSeries();
    setRubberBand(QChartView::HorizontalRubberBand);
    chart = new QChart();
    chart->legend()->hide();
    chart->addSeries(series);
    chart->setTitle("<font size='5'>Power Spectrum Density</font>");
    chart->setBackgroundVisible(false);
    chart->setTheme(QChart::ChartThemeDark);

    axisX = new QValueAxis();
    axisX->setTitleText("Range Gate Index");
    axisX->setLabelFormat("%i");
    axisX->setTickCount(5);
    //axisX->setLabelsVisible(false);
    //chart->addAxis(axisX, Qt::AlignBottom);
    //series->attachAxis(axisX);

    //axisY = new QLogValueAxis();
    axisY = new QValueAxis();
    axisY->setTitleText("PSD Data");
    axisY->setLabelFormat("%g");
    //axisY->setBase(10.0);
    axisY->setMinorTickCount(-1);
    //chart->addAxis(axisY, Qt::AlignLeft);
    //series->attachAxis(axisY);

    chart->setAxisX(axisX, series);
    chart->setAxisY(axisY, series);

    setRenderHint(QPainter::Antialiasing);
    this->setChart(chart);
}

void PSD_Chart_Painter::update_PSD_Chart(double *psd_data, int nRB, int data_num)
{
    series->clear();
    double max_data = 0, min_data = psd_data[0];
    QVector <QPointF> points;
    double ki = nRB * 1.0 / data_num;
    for (int i = 0; i < data_num; i++)
    {
        double temp = psd_data[i];
        {
            points.append(QPointF((double)i * ki, temp));
            max_data = temp > max_data ? temp : max_data;
            min_data = temp < min_data ? temp : min_data;
        }
    }
    series->replace(points);
    axisY->setMax(max_data);
    axisY->setMin(min_data);
}

void PSD_Chart_Painter::update_nRB(int nRB)
{
    axisX->setTickCount(nRB + 1);
    axisX->setRange(0, nRB);
    this->nRB = nRB;
}

void PSD_Chart_Painter::mouseReleaseEvent(QMouseEvent *event)
{
    QChartView::mouseReleaseEvent(event);
    QTimer::singleShot(0, this, SLOT(adjustViewArea()));
}

void PSD_Chart_Painter::adjustViewArea()
{
    int tempMin = floor(axisX->min()), tempMax = ceil(axisX->max());
    tempMin = tempMin < 0 ? 0 : tempMin;
    tempMax = tempMax > nRB ? nRB : tempMax;
    axisX->setRange(tempMin, tempMax);
    axisX->setTickCount(tempMax - tempMin + 1);
}
